package stage1.module4.Q3;

public class TicketThread extends Thread {

    private Test t;

    public TicketThread(Test t) {
        this.t = t;
    }

    @Override
    public void run() {
        long id = currentThread().getId();
        while (true) {
            // 锁定卖票过程，使得同一时间，只有一个线程能够执行卖票
            synchronized (t) {
                if (t.getTicket() > 0) {
                    t.setTicket(t.getTicket() - 1);
                    System.out.println("线程 " + id + " 卖出一张票，剩余票数：" + t.getTicket());
                }
                else {
                    break;
                }
            }
        }
        System.out.println("票已卖完，线程 " + id + " 停止卖票。");
    }
}
